package com.yc.demo.d0729;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/cookie.s")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 发送网络请求的时候，Cookie会在请求头里一起发送给服务器端。
        resp.setContentType("text/html;charset=utf-8");
        final PrintWriter out = resp.getWriter();
        // 获取请求中的cookie数据
        final Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            out.append("<ol>");
            for (Cookie cookie : cookies) {
                out.append("<li>")
                        .append(cookie.getName())
                        .append(" = ")
                        .append(cookie.getValue())
                        .append("</li>");
            }
            out.append("</ol>");
        }

        final String name = req.getParameter("name");
        final String value = req.getParameter("value");
        final String maxAge = req.getParameter("maxAge");
        if (name != null) {
            // 服务器端操作cookie
            Cookie cookie = new Cookie(name, value);
            // 设置有效期, 如果有效期是 0 , 表示删除该cookie
            // 如果不设置有效期, 表示该cookie 在浏览器关闭时, 自动失效
            if(maxAge!=null){
                cookie.setMaxAge( Integer.parseInt(maxAge) );
            }
            // 将cookie 保存到 响应对象中, 发送给浏览器
            resp.addCookie(cookie);
        }
    }
    // cookie.s?name=test&value=abc    添加cookie
    // cookie.s?name=age&maxAge=0       删除cookie
}
